package personal.zq.practice.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.compressors.z.ZCompressorInputStream;

@Slf4j
public class CompressUtil {

    private CompressUtil() {
    }

    /**
     * 解压文件
     *
     * @param path        压缩文件path
     * @param outFileName 解压之后文件名
     * @return 解压之后文件全路径
     */
    public static String deCompress(Path path, String outFileName) {
        int bufferSize = 2048;
        String filePath = path.toFile().getPath();
        if (!Files.exists(path)) {
            log.info(" 文件不存在： {}", filePath);
            return null;
        }
        String outFile = path.getParent() + File.separator + outFileName;

        try (FileInputStream fis = new FileInputStream(filePath);
             FileOutputStream fos = new FileOutputStream(outFile);
             BufferedInputStream bis = new BufferedInputStream(fis);
             ZCompressorInputStream zIn = new ZCompressorInputStream(bis)) {
            byte[] buffer = new byte[bufferSize];
            int len = -1;
            while (-1 != (len = zIn.read(buffer))) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            log.error("解压文件失败", e);
            throw new RuntimeException(e);
        }
        return outFile;
    }
}
